package ui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;

import javax.swing.BorderFactory;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 * Paint lines so the table will look like a Sudoku table
 * @author ido
 */
public class BoardTable extends JTable {

	public BoardTable() {
		super();

	}

	/**
	 * Ctor
	 * @param rowData
	 * @param columnNames
	 */
	public BoardTable(Object[][] rowData, Object[] columnNames) {
		super(rowData, columnNames);
		setColumnWidths(this, new Insets(5, 5, 5, 5), true, true);
		setBorder(BorderFactory.createRaisedBevelBorder());

	}

	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.setColor(Color.BLACK);
		int y = getRowHeight(0);// - 1;
		g.drawLine(0, y*3, getSize().width, y*3);
		g.drawLine(0, y*6, getSize().width, y*6);
		
		// vertical lines
		int x = (int)getCellRect(1, 1, true).getWidth();
		g.drawLine(x*3, 0, x*3, getSize().height);
		g.drawLine(x*6, 0, x*6, getSize().height);
	}

	public void setEditorsRederders() {
		setDefaultRenderer(Object.class, new BoardTableRenderer());
		setDefaultEditor(Object.class, new NumCellEditor());

	}

	/**
	 * Calculate the required width of a table column
	 */
	public static int calculateColumnWidth(JTable table, int columnIndex) {
		int width = 15; // The return value
		int rowCount = table.getRowCount();

		for (int i = 0; i < rowCount; i++) {
			TableCellRenderer renderer = table.getCellRenderer(i, columnIndex);
			Component comp = renderer.getTableCellRendererComponent(table,
					table.getValueAt(i, columnIndex), false, false, i,
					columnIndex);
			int thisWidth = Math.min(5, comp.getPreferredSize().width);
			if (thisWidth > width) {
				width = thisWidth;
			}
		}
		return width;
	}

	/**
	 * Set the widths of every column in a table
	 */
	public static void setColumnWidths(JTable table, Insets insets,
			boolean setMinimum, boolean setMaximum) {
		int columnCount = table.getColumnCount();
		TableColumnModel tcm = table.getColumnModel();
		int spare = (insets == null ? 0 : insets.left + insets.right);

		for (int i = 0; i < columnCount; i++) {
			int width = calculateColumnWidth(table, i);
			width += spare;

			TableColumn column = tcm.getColumn(i);
			column.setPreferredWidth(width);
			if (setMinimum == true) {
				column.setMinWidth(width);
			}
			if (setMaximum == true) {
				column.setMaxWidth(width);
			}
		}
	}

}
